package com.module.launcher.view

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.widget.TextViewCompat
import androidx.fragment.app.Fragment
import com.luck.picture.lib.config.PictureConfig.EXTRA_POSITION
import com.module.app.arouter.ArouterUtils
import com.module.app.arouter.service.ILoginService
import com.module.app.base.BaseActivity
import com.module.app.ext.loginFlow
import com.module.app.ext.loginTopFlow
import com.module.app.pop.CommonPop
import com.module.app.pop.ProgressPop
import com.module.app.utils.AutoSkinNightUtils
import com.module.app.utils.UpdateUtils
import com.module.app.utils.UserUtils
import com.module.base.cache.CacheSDK
import com.module.base.utils.ToastUtils
import com.module.base.utils.ViewPager2Helper
import com.module.base.widget.pager.MyFragmentAdapter
import com.module.frame.ext.observe
import com.module.launcher.R
import com.module.launcher.databinding.LauncherActivityMianBinding
import com.module.launcher.model.MainViewModel
import com.module.launcher.utils.checkServiceUtils
import com.module.launcher.view.fragment.HomeHomeFragment
import com.module.launcher.view.fragment.HomeMessageFragment
import com.module.launcher.view.fragment.HomeMyFragment
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView.OnPagerTitleChangeListener

open class MainActivity : BaseActivity<MainViewModel, LauncherActivityMianBinding>() {

    private var defaultPosition = 0
    var progressPop: ProgressPop? = null
    private var titles: MutableList<Int> = mutableListOf()
    private val fragmentList: MutableList<Fragment> = mutableListOf()
    private val commonNavigator: CommonNavigator by lazy {
        CommonNavigator(this)
    }
    private val mLoginService: ILoginService by lazy {
        ArouterUtils.getLoginService()
    }
    private var mBackPressed: Long = 0


    override fun bingViewModel() {
        mDatabind.vm = mViewModel
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        defaultPosition = intent.getIntExtra(EXTRA_POSITION, 0)
        mDatabind.viewPager.currentItem = defaultPosition
    }

    override fun getIntent(intent: Intent) {
        super.getIntent(intent)
        defaultPosition = intent.getIntExtra(EXTRA_POSITION, 0)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        //监听自动深夜模式,要在onCreate 前面
        AutoSkinNightUtils.bindActivity(getActivity())
        super.onCreate(savedInstanceState)
    }

    override fun initView() {
        super.initView()
        initViewPage()
    }

    override fun initListener() {
        super.initListener()
        //登录监听
        observe(loginFlow) {
            if (it) {
                checkServiceUtils.check()
            } else {
                checkServiceUtils.destroy()
            }
        }
        //账号被顶监听
        observe(loginTopFlow) {
            if (!UserUtils.isLogin()) {
                return@observe
            }
            //全局弹窗
            CommonPop.Builder(getContext())
                .setContent(R.string.launcher_login_top_content)
                .setCanceledOnTouchOutside(false)
                .setCancelable(false)
                .setOnConfirmListener { //退出登录
                    logout(true)
                }
                .show()
        }
        //公告监听
        observe(mViewModel.noticeFlow) {
            showNotice(it)
        }
        //更新监听
        observe(mViewModel.updateFlow) {
            if (it) {
                setUpDate()
            }
        }

    }

    override fun initData() {
        super.initData()
        mViewModel.getConfig()
        //引导评价
        com.module.app.utils.EvaluateUtils.onGuideEvaluate()
    }

    private fun initViewPage() {
        titles.add(R.string.launcher_club)
        titles.add(R.string.launcher_message)
        titles.add(R.string.launcher_my)
        for (id in titles) {
            when {
                id === R.string.launcher_club -> {
                    fragmentList.add(HomeHomeFragment())
                }
                id === R.string.launcher_message -> {
                    fragmentList.add(HomeMessageFragment())
                }
                id === R.string.launcher_my -> {
                    fragmentList.add(HomeMyFragment())
                }
            }
        }
        val adapter = MyFragmentAdapter(this, fragmentList)
        mDatabind.viewPager.adapter = adapter
        mDatabind.viewPager.offscreenPageLimit = fragmentList.size
        commonNavigator.isAdjustMode = true
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return if (titles == null) 0 else titles.size
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val commonPagerTitleView = CommonPagerTitleView(context)
                commonPagerTitleView.setContentView(R.layout.launcher_main_pager_title_layout)

                // 初始化
                val titleText = commonPagerTitleView.findViewById<View>(R.id.tv_text) as TextView
                titleText.setText(titles.get(index))
                val titleImg = commonPagerTitleView.findViewById<View>(R.id.tv_img) as ImageView
                commonPagerTitleView.onPagerTitleChangeListener =
                    object : OnPagerTitleChangeListener {
                        override fun onSelected(index: Int, totalCount: Int) {
                            TextViewCompat.setTextAppearance(titleText, R.style.TextTabBottom)
                            when {
                                titles[index] === R.string.launcher_club -> {
                                    titleImg.setImageResource(R.drawable.launcher_icon_lock_select)
                                }
                                titles[index] === R.string.launcher_message -> {
                                    titleImg.setImageResource(R.drawable.launcher_icon_activity_select)
                                }
                                titles[index] === R.string.launcher_my -> {
                                    titleImg.setImageResource(R.drawable.launcher_icon_my_select)
                                }
                            }
                        }

                        override fun onDeselected(index: Int, totalCount: Int) {
                            TextViewCompat.setTextAppearance(titleText, R.style.TextTabBottom2)
                            when {
                                titles[index] === R.string.launcher_club -> {
                                    titleImg.setImageResource(R.drawable.launcher_icon_lock)
                                }
                                titles[index] === R.string.launcher_message -> {
                                    titleImg.setImageResource(R.drawable.launcher_icon_activity)
                                }
                                titles[index] === R.string.launcher_my -> {
                                    titleImg.setImageResource(R.drawable.launcher_icon_my)
                                }
                            }
                        }

                        /**
                         * 由于禁止了动画，所以不会调用
                         */
                        override fun onLeave(
                            index: Int,
                            totalCount: Int,
                            leavePercent: Float,
                            leftToRight: Boolean
                        ) {
                            //                        titleImg.setScaleX(1.0f + (0.7f - 1.0f) * leavePercent);
                            //                        titleImg.setScaleY(1.0f + (0.7f - 1.0f) * leavePercent);
                        }

                        /**
                         * 由于禁止了动画，所以不会调用
                         */
                        override fun onEnter(
                            index: Int,
                            totalCount: Int,
                            enterPercent: Float,
                            leftToRight: Boolean
                        ) {
                            //                        titleImg.setScaleX(0.7f + (1.0f - 0.7f) * enterPercent);
                            //                        titleImg.setScaleY(0.7f + (1.0f - 0.7f) * enterPercent);
                        }
                    }
                commonPagerTitleView.setOnClickListener {
                    mDatabind.viewPager.setCurrentItem(
                        index,
                        false
                    )
                }
                return commonPagerTitleView
            }

            override fun getIndicator(context: Context): IPagerIndicator? {
                return null
            }
        }
        mDatabind.indicator.navigator = commonNavigator
        ViewPager2Helper.bind(mDatabind.indicator, mDatabind.viewPager)
        mDatabind.viewPager.currentItem = defaultPosition
        mDatabind.viewPager.isUserInputEnabled = false
    }

    open fun showNotice(content: String?) {
        if (TextUtils.isEmpty(content)) {
            return
        }
        Handler(Looper.getMainLooper()).postDelayed(Runnable {
            if (getActivity() == null || getActivity().isFinishing) {
                return@Runnable
            }
            com.module.app.pop.CommonPop.Builder(getContext())
                .setContent(content)
                .show()
        }, 3000)
    }

    open fun setUpDate() {
        val updateCode = CacheSDK.get(com.module.app.bean.IType.ICache.UPDATE_CODE, Int::class.java)
        if (updateCode == com.module.app.bean.ConfigBean.getInstance().appVersionCode) {
            return
        }
        //弹窗更新
        progressPop = ProgressPop.Builder(getContext())
            .setContentGravity(Gravity.LEFT)
            .setTitle(R.string.update_title)
            .setProgressTitle(R.string.downloading)
            .setContent(com.module.app.bean.ConfigBean.getInstance().appVersionContent)
            .setAutoDismiss(false)
            .setCancelButton(R.string.update_cancel)
            .setConfirmButton(R.string.right_off_update)
            .setOnCancelListener { progressPop?.dismiss() }
            .setOnConfirmListener {
                UpdateUtils.update(
                    getContext(),
                    com.module.app.bean.ConfigBean.getInstance().downloadApk,
                    com.module.app.bean.ConfigBean.getInstance().appVersionName
                )
            }
            .create()
        progressPop?.setOnDismissListener(com.module.app.pop.CommonPop.OnDismissListener {
            CacheSDK.put(
                com.module.app.bean.IType.ICache.UPDATE_CODE,
                com.module.app.bean.ConfigBean.getInstance().appVersionCode
            )
        })
        progressPop?.show()
    }

    /**
     *  退出登录
     */
    open fun logout(isGo: Boolean) {
        mLoginService?.logout()
        if (isGo) {
            mLoginService?.startLogin(getContext())
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        for (fragment in fragmentList) {
            fragment.onActivityResult(requestCode, resultCode, data)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        com.module.app.utils.EvaluateUtils.destroy()
    }

    override fun onBackPressed() {
        if (mBackPressed + 2000 > System.currentTimeMillis()) {
            super.onBackPressed()
            return
        } else {
            ToastUtils.showShort("再点一次退出程序")
            mBackPressed = System.currentTimeMillis()
        }
    }
}